package org.opens.factory.lottery;

import org.opens.factory.lottery.impl.EmptyLotteryApiImpl;
import org.opens.factory.lottery.impl.JuHeLotteryApiImpl;
import org.opens.factory.lottery.other.LotteryApiTypes;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class LotteryApiFactory implements InitializingBean {

    @Value("${lottery.type}")
    public String LotteryType;

    @Autowired
    private ApplicationContext applicationContext;

    private Map<String, LotteryApi> lotteryApiMap = new HashMap<>();

    public LotteryApi get() {
        LotteryApi lotteryApi = lotteryApiMap.get(LotteryType);
        // 配置不当则返回空实现;
        if (lotteryApi == null) {
            return lotteryApiMap.get(LotteryApiTypes.EMPTY);
        }
        return lotteryApi;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        lotteryApiMap.put(LotteryApiTypes.JUHE, applicationContext.getBean(JuHeLotteryApiImpl.class));
        lotteryApiMap.put(LotteryApiTypes.EMPTY, applicationContext.getBean(EmptyLotteryApiImpl.class));
    }
}
